const Controller = require('egg').Controller;

class WeixinController extends Controller {

    async configinfo () {

        const { ctx, app } = this;


        let { url, company_code, pay_company_code } = ctx.request.body;

        console.log('configinfo');
        console.log(url);

        //如果没传默认香草
        if(company_code == undefined){
            company_code = 'LW88888';
        }

        // ctx.logger.info('url : ' + url);
        // ctx.logger.info('company_code : ' + company_code);
        // ctx.logger.info('pay_company_code : ' + pay_company_code);

        //const pay_company_code = 'LW88888';

        let companyInfo = {};
        let result = {};
        let appid = '';

        if(pay_company_code != undefined){

            companyInfo = await ctx.service.company.info(pay_company_code);

            const paycompanyInfo = await ctx.service.company.infoByWXid(companyInfo.pay_wxid);

            appid = paycompanyInfo.appid;

            result = await ctx.service.weixin.getSignature(companyInfo.pay_wxid, url);

        }else{

            companyInfo = await ctx.service.company.info(company_code);

            //ctx.logger.info(companyInfo);

            appid = companyInfo.appid;

            //ctx.logger.info(appid);

            result = await ctx.service.weixin.getSignature(companyInfo.wxid, url);

            //ctx.logger.info(result);

        }

        ctx.helper.success({
            ...result,
            appid,
        });
    }

    //向商家支付
    async createOrder4Merchant () {

        const { ctx, app } = this;

        const { code } = ctx.request.body;
        //const pay_company_code = 'LW88888';
        const pay_company_code = 'LW99999';

        const paycompanyInfo = await ctx.service.company.info(pay_company_code);

        const total_fee = await app.redis.get('system').hget('juyou.order.' + code, 'total_fee');
        //app.logger.info('total_fee : ' + total_fee);

        const subject = await app.redis.get('system').hget('juyou.order.' + code, 'subject');
        //app.logger.info('subject : ' + subject);

        const sale_code = await app.redis.get('system').hget('juyou.order.' + code, 'sale_code');
        //app.logger.info('sale_code : ' + sale_code);

        const xml = await ctx.service.weixin.createOrder2Merchant(code, paycompanyInfo.pay_wxid, subject, parseFloat(total_fee * 100).toFixed(0), sale_code);

        // app.logger.info(xml);
        // app.logger.info('支付商家调微信统一下单。。。');

        const result = await ctx.curl('https://api.mch.weixin.qq.com/pay/unifiedorder', {
            method: 'POST',
            content: xml,
            dataType: 'text',
        });

        // console.log(result);

        // app.logger.info(result);

        const result1 = app.x2js.xml2js(result.data);

        //app.logger.info(result1);

        const r = result1.xml;

        if(r.return_code == 'SUCCESS' && r.result_code == 'SUCCESS'){
            ctx.helper.success(r.code_url);
        }
        else{
            ctx.helper.error('微信下单失败');
        }

    }

    async createOrder () {

        const { ctx, app } = this;

        const { code, company_code, pay_company_code } = ctx.request.body;

        // ctx.logger.info(code);
        // ctx.logger.info(company_code);
        // ctx.logger.info(pay_company_code);

        const sessionid = ctx.cookies.get('juyou-ticket-' + company_code);

        //ctx.logger.info('sessionid : ' + sessionid);

        const str_pay_wxid = await app.redis.get('member').hget('juyou_ticket_' + sessionid, 'pay_wxid');

        //ctx.logger.info('str_pay_wxid : ' + str_pay_wxid);

        const paycompanyInfo = await ctx.service.company.info(pay_company_code);


        // ctx.logger.info('paycompanyInfo : ');
        // ctx.logger.info(paycompanyInfo);


        let obj_pay_wxid = {};
        if(str_pay_wxid != null){
            obj_pay_wxid = JSON.parse(str_pay_wxid);
        }

        const openid = obj_pay_wxid[paycompanyInfo.pay_wxid];

        //const pay_company_code = 'LW88888';

        // for(let k in obj_pay_wxid){
        //     // let arr = k.split('_');
        //     // const c = arr[0];
        //     // const p = arr[1];
        //     // if(c == pay_company_code){
        //     //     openid = obj_pay_wxid[k];
        //     // }
        // }

        if(openid == undefined){
            ctx.helper.error(123, '支付openid有误');
            return;
        }

        //app.logger.info('juyou.order.' + code);

        const total_fee = await app.redis.get('system').hget('juyou.order.' + code, 'total_fee');

        //app.logger.info('total_fee : ' + total_fee);

        const subject = await app.redis.get('system').hget('juyou.order.' + code, 'subject');

        //app.logger.info('subject : ' + subject);

        const xml = await ctx.service.weixin.createOrder(code, pay_company_code, openid, subject, parseFloat(total_fee * 100).toFixed(0));

        // app.logger.info(xml);
        // app.logger.info('调微信统一下单。。。');

        const result = await ctx.curl('https://api.mch.weixin.qq.com/pay/unifiedorder', {
            method: 'POST',
            content: xml,
            dataType: 'text',
        });

        // console.log(result);

        // app.logger.info(result);

        const result1 = app.x2js.xml2js(result.data);

        // app.logger.info('dddddd');
        // app.logger.info(result1);


        const r = result1.xml;

        if(r.return_code == 'SUCCESS' && r.result_code == 'SUCCESS'){

            //const paycompanyInfo0 = await ctx.service.company.info(pay_company_code);

            const xx = await ctx.service.company.infoByWXid(paycompanyInfo.pay_wxid);
            
            const rr = await ctx.service.weixin.getPaySignature(xx.wxid, xx.appid, r.prepay_id, xx.md5_key);

            //app.logger.info(rr);

            ctx.helper.success(rr);

        }
        else{
            ctx.helper.error('微信下单失败');
        }

    }




    async paycallback () {

        const { ctx, app } = this;
        //ctx.logger.info('支付成功后的微信回调');

        let data = '';
        let json = {};
        ctx.req.setEncoding('utf8');
        ctx.req.on('data',function(chunk){
           data += chunk;
        });
        
        const wxres = await new Promise(resolve =>{
            ctx.req.on('end',function(){
                const aaaa = app.x2js.xml2js(data);
                resolve(aaaa);
            });
        });

        ctx.logger.info(wxres);

        const wxInfo = await ctx.service.company.infoByWXid(wxres.xml.attach);

        //ctx.logger.info(wxInfo);

        const checkresult = await ctx.service.weixin.checkSign(wxres.xml, wxInfo.md5_key);

        ctx.logger.info('签名验证结果 : ' + checkresult);

        if(checkresult){
            const para = {
                cash_fee : parseFloat(wxres.xml.cash_fee).toFixed(0),  //现金支付金额

                //应结订单金额=订单金额-非充值代金券金额，应结订单金额<=订单金额。
                //记录应结金额，是实际入账金额，退款时，应该用这个金额而不是 用户实际支付金额。
                //例如用户支付100元的订单， 用了8元的优惠券，实际支付92元。
                //系统收到的金额 应该是应结金额（100），所以应该按照100元退，这样银行会扣掉8元优惠券，返回给用户92元。
                //而不是按照92元退，这样用户就会收到92-8=84元，少了8元！ 
                //cash_fee : parseFloat(wxres.xml.settlement_total_fee).toFixed(0),  //应结订单金额
                //取不到

                ordercode : wxres.xml.out_trade_no,
                openid : wxres.xml.openid,
                transaction_id : wxres.xml.transaction_id,
                time_end : wxres.xml.time_end,
                trade_type : wxres.xml.trade_type,
                wxid : wxres.xml.attach,
            };

            const r = await ctx.service.pay.saveCallback(para);

            //ctx.logger.info(r);

            let result = {
                xml : {
                    return_code : 'SUCCESS',
                    return_msg : 'OK'
                }
            };

            const xml = app.x2js.js2xml(result);

            ctx.body = xml;
        }else{
            ctx.logger.info('签名验证结果错误。');
            ctx.logger.info(wxres.xml);
            ctx.logger.info(wxInfo.md5_key);
        }
        
    }





    async refundcallback () {

        const { ctx, app } = this;
        ctx.logger.info('退款成功后的微信回调');

        // let data = '';
        // let json = {};
        // ctx.req.setEncoding('utf8');
        // ctx.req.on('data',function(chunk){
        //    data += chunk;
        // });
        
        // const wxres = await new Promise(resolve =>{
        //     ctx.req.on('end',function(){
        //         const aaaa = app.x2js.xml2js(data);
        //         resolve(aaaa);
        //     });
        // });

        // ctx.logger.info(wxres);

        // const wxInfo = await ctx.service.company.infoByWXid(wxres.xml.attach);

        // ctx.logger.info(wxInfo);

        // const checkresult = await ctx.service.weixin.checkSign(wxres.xml, wxInfo.md5_key);

        // ctx.logger.info('签名验证结果 : ' + checkresult);

        // if(!checkresult){
            
        // }


        // const para = {
        //     cash_fee : wxres.xml.cash_fee,
        //     ordercode : wxres.xml.out_trade_no,
        //     openid : wxres.xml.openid,
        //     transaction_id : wxres.xml.transaction_id,
        //     time_end : wxres.xml.time_end,
        //     trade_type : wxres.xml.trade_type,
        //     wxid : wxres.xml.attach,
        // };



        // const r = await ctx.service.pay.saveCallback(para);

        // ctx.logger.info(r);


        let result = {
            xml : {
                return_code : 'SUCCESS',
                return_msg : 'OK'
            }
        };

        const xml = app.x2js.js2xml(result);

        ctx.body = xml;
    }


    async orderMsg () {

        const { ctx, app } = this;

        const { company_code, rurl, code } = ctx.query;

        //const company_code1 = 'LW88888';

        const companyInfo = await ctx.service.company.info(company_code);

        //const template_id = 'UslXrtpUQNSk1fLpVXDiaTdbF6_aWbpYMXTXDP1l1A4';
        //const template_id = companyInfo.msg_template;

        const uuid = await ctx.service.util.uuid(40, 16);
        const mm = company_code + '@dlq@' + rurl + '@dlq@' + code;

        await app.redis.get('tmp').set(uuid, mm);
        await app.redis.get('tmp').expire(uuid, 60 * 60 * 24);

        const callback = 'https://api.hidlq.com/v1/pn/ordermsgcallback';

        let wxurl = 'https://mp.weixin.qq.com/mp/subscribemsg?action=get_confirm' + 
        '&appid=' + companyInfo.appid +
        '&scene=1000'+
        '&template_id=' + companyInfo.msg_template + 
        '&redirect_url=' + encodeURIComponent(callback) +
        '&reserved=' + uuid + 
        '#wechat_redirect';

        //ctx.logger.info(wxurl);

        ctx.redirect(wxurl);
    }

    async orderMsgCallback () {

        const { ctx, app } = this;

        const {openid, template_id, action, scene, reserved} = ctx.query;

        // ctx.logger.info('openid : ' + openid);
        // ctx.logger.info('template_id : ' + template_id);
        // ctx.logger.info('action : ' + action);
        // ctx.logger.info('scene : ' + scene);
        // ctx.logger.info('reserved : ' + reserved);

        //const msg = await app.redis.get('tmp').hget('dlq_tmp', reserved);
        const msg = await app.redis.get('tmp').get(reserved);
        //app.redis.get('tmp').del('dlq_tmp', reserved);

        const arr = msg.split('@dlq@');

        if(arr.length !== 3){
            ctx.helper.error(104, 'reserved 不正确');
            return;
        }

        const company_code = arr[0];
        const rurl = arr[1];
        const order_code = arr[2];
        //const company_code = arr[3];

       // ctx.logger.info('company_code1 : ' + company_code1);
        // ctx.logger.info('rurl : ' + rurl);
        // ctx.logger.info('title : ' + order_code);
        // ctx.logger.info('company_code : ' + company_code);


        if(action == 'confirm'){
            const subject = await app.redis.get('system').hget('juyou.order.' + order_code, 'subject');
            //app.logger.info('subject : ' + subject);

            const companyInfo = await ctx.service.company.info(company_code);
            const token = await ctx.service.company.accesstoken(companyInfo.wxid);

            //ctx.logger.info('token:' + token);

            const url = 'https://api.weixin.qq.com/cgi-bin/message/template/subscribe?access_token=' + token.access_token;

            let url1 = 'https://shop.hidlq.com/#/orderinfo/' + order_code + '?company_code=' + company_code;

            const result = await ctx.curl(url, {
                method: 'POST',
                contentType: 'json',
                data: {
                    touser : openid,
                    template_id,
                    //'url' : url1,
                    'url' : rurl,
                    scene,
                    'title' : subject,
                    data : {
                        content : {
                            color : '#000',
                            value : '点击查看订单',
                        }
                    }
                },
                dataType: 'json',
            });
        }

        ctx.redirect(rurl);
        
    }


    async setToken () {

        const { app } = this;

        await app.runSchedule('update_accesstoken');

        this.ctx.helper.success('ok');
    }
    
}
module.exports = WeixinController;



